<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="项目档案编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalNo">
                  <a-input disabled v-model="model.finalNo" placeholder="请输入项目档案编号"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectName">
                  <a-input disabled v-model="model.projectName" placeholder="请输入项目名称"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同总额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractTotalMoney">
                  <a-input-number disabled :max="99999999" :min="0"   v-model="model.contractTotalMoney" placeholder="请输入合同总额" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="应收款总额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivablesPaymentMoney">
                  <a-input-number disabled :max="99999999" :min="0" v-model="model.receivablesPaymentMoney" placeholder="请输入应收款总额" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="实收款总额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realCollectionPaymentMoney">
                  <a-input-number disabled :max="99999999" :min="0"   v-model="model.realCollectionPaymentMoney" placeholder="请输入实收款总额" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="扣款总额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deductMoney">
                  <a-input-number disabled :max="99999999" :min="0"   v-model="model.deductMoney" placeholder="请输入扣款总额" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="最近到款日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lastPaymentTime">
                  <j-date disabled placeholder="请选择最近到款日期" v-model="model.lastPaymentTime"  style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="进度状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractCompleteStatus">
                  <a-input disabled  placeholder="请输入进度状态"  ></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="进度信息">
<!--            <div class="table-operator">-->
<!--              <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
<!--            </div>-->
            <div>
              <a-table
                ref="table"
                size="middle"
                bordered
                rowKey="key"
                :scroll="{x:scrollX}"
                :components="draggableComponent"
                :columns="defColumns"
                :dataSource="dataSource"
                :pagination="false"
                :loading="loading"
                class="j-table-force-nowrap"
              >
                <span slot="action" slot-scope="text, record">
                  <a @click="handleEdit(record)">编辑</a>
                </span>
              </a-table>
            </div>
          </a-collapse-panel>
        </a-collapse>
        <erp-progress-payment-node-modal ref="paymentNode" @ok="modalFormOk" @dataOne="dataOne"></erp-progress-payment-node-modal>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import ErpProgressPaymentNodeModal from './ErpProgressPaymentNodeModal.vue'
  import { DragResizable } from '@/mixins/DragResizable'
  export default {
    name: 'ErpProgressPaymentForm',
    components: {
      ErpProgressPaymentNodeModal
    },
    mixins: [DragResizable],
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          nodeList: [],
          projectId: ''
        },
        labelCol: {},
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        loading: false,
        validatorRules: {
          paymentMoney: [
            { required: true, message: '请输入应收款金额!'},
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          realCollectionDate: [
            { required: true, message: '请输入实收款金额!'},
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
        },
        url: {
          add: "/api/erp/progress/erpProgressPaymentNode/addPaymentNode",
          edit: "/api/erp/progress/erpProgressPayment/edit",
          queryById: "/api/erp/progress/erpProgressPayment/queryById"
        },
        dataSource: [],
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            fixed: 'left',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '款项名称',
            align: 'center',
            dataIndex: 'nodeName',
            width:200,
            ellipsis: true,
          },
          {
            title: '应收款金额（元）',
            align: 'center',
            dataIndex: 'paymentMoney',
            width:170,
            ellipsis: true,
          },
          {
            title: '预计回款日期',
            align: 'center',
            dataIndex: 'preCollectionDate',
            width:133,
            ellipsis: true,
          },
          {
            title: '款项节点说明',
            align: 'center',
            dataIndex: 'nodeDesc',
            width:300,
            ellipsis: true,
          },
          // {
          //   title: '关联合同进度节点',
          //   align: 'center',
          //   dataIndex: 'contractNodeId',
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            // fixed:"right",
            width:150,
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action' }
          }
        ],
        activeKey: ['1','2'],
        paymentNodeUrl: {
          list: '/api/erp/progress/erpProgressPaymentNode/queryListByContractId',
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.customKey = 'defColumns'
      this.defColumnswidth = this.defColumns.map(val => {
        return val.width
      })
    },
    methods: {
      handleAdd() {
        this.$refs.paymentNode.add(this.model);
        this.$refs.paymentNode.title = '新增收款进度节点';
        this.$refs.paymentNode.disableSubmit = false;
      },
      handleEdit(record) {
        this.$refs.paymentNode.edit(record);
        this.$refs.paymentNode.title = '编辑收款进度节点';
        this.$refs.paymentNode.disableSubmit = false;
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.initDictConfig()
      },
      initDictConfig() {
        if (!this.paymentNodeUrl.list) {
          this.$message.error('请设置paymentNodeUrl.list属性!')
          return
        }
        console.log('this.model',this.model)
        var params = {
          pageNo: 1,
          pageSize: 10,
          column: 'createTime',
          order: 'desc',
          contractId: this.model.contractId
        }
        this.loading = true
        getAction(this.paymentNodeUrl.list, params).then(res => {
          console.log(res);
          if (res.success) {
            this.dataSource = res.result || res.result.records
            this.dataSource.forEach((item,index) => {
              item.key = index
            })
          } else {
            this.dataSource = [];
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this[this.customKey].forEach((val,index) => {
          val.width = this[this.customKey+'width'][index]
        })
        this.initDictConfig()
      },
      submitForm () {
        const that = this;
        if(this.dataSource.length !== 0){
          this.dataSource.forEach((val,index) => {
            if(!val.sortOrder){
              val.sortOrder = index + 1
            }
          })
          this.model.nodeList = Object.assign([],this.dataSource)
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = this.url.add;
            let method = 'post';
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      dataOne(data, flag) {
        console.log('data,flag', data, flag)
        if (flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key,1,data);
        }
      },
    }
  }
</script>
